package com.lzyyj.gmis.base.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ExcelFile {
	
	private FileInputStream fileInputStream;
	
	private Workbook workbook = null;

	public ExcelFile(File file){
		try {
			this.fileInputStream = new FileInputStream(file);
			workbook = WorkbookFactory.create(fileInputStream);
		} catch (Exception e) {
		}
	}

	public ExcelFile(FileInputStream fileInputStream){
		this.fileInputStream = fileInputStream;
		try {
			workbook = WorkbookFactory.create(fileInputStream);
		} catch (Exception e) {
		}
	}
	
	public static ExcelFile getInstance(File file) {
		ExcelFile excelFile = new ExcelFile(file);
		return excelFile;
	}

	/**
	 * 是否是有效的Excel文件
	 * @return
	 */
	public boolean isValidate() {
		return (workbook!=null);
	}

	public Workbook getWorkbook() {
		return workbook;
	}

	/**
	 * 解析所包含的数据表
	 * @return
	 */
	public List<DataTable> parseDataTables() {
		List<DataTable> dataTables = new ArrayList<DataTable>();
		
		if(workbook!=null) {
			for(int i=0;i<workbook.getNumberOfSheets();i++){
				// 解析各工作表中的数据表
				List<DataTable> list = DataTable.praseDataTables(workbook.getSheetAt(i),i);
				for(DataTable excelDataTable:list) {
					dataTables.add(excelDataTable);
				}
			}
		}
		
		return dataTables;
	}

	public void close() {
		if(workbook!=null) {
			try {
				workbook.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			workbook = null;
		}
		if(fileInputStream!=null) {
			try {
				fileInputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		fileInputStream = null;
	}

}
